package com.YCH.behavior.service.impl;

import com.YCH.behavior.service.AppCollectionBehaviorService;
import com.YCH.model.behavior.dtos.CollectionBehaviorDto;
import com.YCH.model.behavior.pojos.TbCollectionBehavior;
import com.YCH.model.common.dtos.ResponseResult;
import com.YCH.model.common.enums.AppHttpCodeEnum;
import com.YCH.model.mappers.app.TbCollectionBehaviorMapper;
import com.YCH.model.user.pojos.TbUser;
import com.YCH.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
@SuppressWarnings("all")
public class AppCollectionBehaviorServiceImpl implements AppCollectionBehaviorService {
    @Autowired
    private TbCollectionBehaviorMapper tbCollectionBehaviorMapper;

    @Override
    public ResponseResult saveCollectionBehavior(CollectionBehaviorDto dto) {
        TbUser user = AppThreadLocalUtils.getUser();
        // 用户和用户id不能同时为空
        if (user == null && dto.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long userId = null;
        if (user != null) {
            userId = user.getId();
        }
        if(dto.getUserId()!=null){
            userId = dto.getUserId();
        }
        // 查询该用户是否已经取消收藏
        TbCollectionBehavior tbCollectionBehavior = tbCollectionBehaviorMapper.selectForUserId(userId, dto.getArticleId(), dto.getType());
        // 操作为零就是收藏
        if (dto.getOperation() == 0 && tbCollectionBehavior == null) {
            // 当数据库中没有查到该用户取消收藏，且用户操作是收藏，就插入收藏
            TbCollectionBehavior alb = new TbCollectionBehavior();
            alb.setUserId(userId);
            alb.setCreatTime(new Date());
            alb.setArticleId(dto.getArticleId());
            alb.setType(dto.getType());
            alb.setOperation(dto.getOperation());
            return ResponseResult.okResult(tbCollectionBehaviorMapper.insert(alb));
        } else {// 否则就是取消收藏/恢复收藏
            TbCollectionBehavior alb = new TbCollectionBehavior();
            alb.setUserId(userId);
            alb.setArticleId(dto.getArticleId());
            alb.setOperation(dto.getOperation());
            return ResponseResult.okResult(tbCollectionBehaviorMapper.updata(alb));
        }
    }
}
